package com.st.warehouse.ui.adapter;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.st.warehouse.R;
import com.st.warehouse.bean.Sign;
import com.st.warehouse.service.MyService;
import com.st.warehouse.utils.Data;
import com.st.warehouse.utils.DialogUtils;
import com.st.warehouse.utils.PermissionChecker;
import com.st.warehouse.utils.RetrofitUtil;
import com.st.warehouse.utils.SystemUtils;

import java.io.IOException;
import java.util.ArrayList;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 停点名称列表-适配类
 */
public class YSignAppAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    Context baseActivity;
    ArrayList<Sign> list;//车位数据
    private OnItemClickListener onItemClickListener;
    private View view1;
    private EditText edit_name;

    public interface EventListener{
        void updateSuccess();
    }
    //注入
    private EventListener eventListener;
    public void setEventListener(EventListener eventListener){
        this.eventListener = eventListener;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_sign, parent, false);
        view1 = LayoutInflater.from(parent.getContext()).inflate(R.layout.dialog_update_phone, parent, false);
        initVice();
        return new ViewHolder(view);
    }

    // 定义接口用于回调点击事件
    public interface OnItemClickListener {
        void onItemClick(View v,int position);
    }

    public YSignAppAdapter(ArrayList<Sign> list, Context baseActivity) {
        this.list = list;
        this.baseActivity = baseActivity;
    }

    // 设置点击事件监听器
    public void setOnItemClickListener(OnItemClickListener listener) {
        this.onItemClickListener = listener;
    }

    public void setData(ArrayList<Sign> studentList) {
        this.list = studentList;
    }
    //加载新的数据
    public void addData(ArrayList<Sign> newData) {
        // 将新数据添加到现有数据列表
        list.addAll(newData);
    }
    private MyService myService;//初始化
    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder viewHolder,@SuppressLint("RecyclerView") int position) {
        ViewHolder holder = (ViewHolder) viewHolder;
        Sign sign = list.get(position);
        holder.userPhone.setText(sign.getUserPhone());
        String info = "";
        if (Data.isNotNull(sign.getUserName()) && Data.isNotNull(sign.getUserPosition())){
            info = sign.getUserName()+"-"+sign.getUserPosition();
        }else if (Data.isNull(sign.getUserPosition())){
            info = sign.getUserName();
        }
        holder.info.setText(info);
        holder.freshTime.setText(sign.getFreshTime());
        holder.signInfo.setText(sign.getSignInfo());
        if ("今日已签到".equals(sign.getSignInfo())){
            holder.signInfo.setTextColor(baseActivity.getColor(R.color.green2));
            holder.info.setTextColor(baseActivity.getColor(R.color.green2));
            holder.userPhone.setTextColor(baseActivity.getColor(R.color.green2));
        }else if ("今日未签到".equals(sign.getSignInfo())){
            holder.signInfo.setTextColor(baseActivity.getColor(R.color.red));
        }

        //点击复制文本
        holder.userPhone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setClickableWithDelay(holder.userPhone, 1000);//按钮禁止连点
                final String textToCopy = ((TextView) view).getText().toString();
                //SystemUtils.showCopyPopupWindow(view.getContext(), view, textToCopy);

                //直接复制
                // 获取剪贴板管理器
                ClipboardManager clipboardManager = (ClipboardManager) baseActivity.getSystemService(Context.CLIPBOARD_SERVICE);
                // 创建 ClipData 对象
                ClipData clipData = ClipData.newPlainText("text", textToCopy);
                // 将 ClipData 对象放入剪贴板
                clipboardManager.setPrimaryClip(clipData);
                Toast.makeText(baseActivity, "复制成功", Toast.LENGTH_SHORT).show();

                //
                holder.signInfo.setText("今日已签到");
                holder.userPhone.setTextColor(baseActivity.getColor(R.color.green2));
                holder.info.setTextColor(baseActivity.getColor(R.color.green2));
                holder.signInfo.setTextColor(baseActivity.getColor(R.color.green2));
                String phoneNo = holder.userPhone.getText().toString();
                toSign(phoneNo);
            }
        });

        //修改姓名
        holder.signInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String userPhone = sign.getUserPhone();
                updateName(userPhone);
            }
        });
    }

    private void updateName(String userPhone) {
        // 如果 view1 已经有父视图，先移除它
        if (view1.getParent() != null) {
            ((ViewGroup) view1.getParent()).removeView(view1);
        }
        AlertDialog.Builder dialog = new AlertDialog.Builder(baseActivity);
        dialog.setView(view1);
        final AlertDialog dialog2 = dialog.create();
        dialog2.show();

        //=====================================版本组件==============================
        //
        edit_name = view1.findViewById(R.id.edit_name);
        EditText edit_order = view1.findViewById(R.id.edit_order);//
        Button btn_speach = view1.findViewById(R.id.btn_speach);//
        Button btn_cancel = view1.findViewById(R.id.btn_cancel);//取消
        Button btn_ok = view1.findViewById(R.id.btn_ok);//确认
        myService = RetrofitUtil.build(MyService.class);//初始化网络请求
        myService.getName(userPhone).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    if (response.isSuccessful()) {
                        JSONObject data = RetrofitUtil.getDataFromResponse(response);
                        if (200 == data.getInteger("code")) {
                            String userName = data.getJSONObject("data").getString("userName");
                            String userOrder = data.getJSONObject("data").getString("userOrder");
                            if (Data.isNotNull(userName)){
                                edit_name.setText(userName);
                            }else {
                                edit_name.setText("");
                            }
                            if (Data.isNotNull(userOrder)){
                                edit_order.setText(userOrder);
                            }else {
                                edit_order.setText("");
                            }
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable throwable) {
                SystemUtils.invokeHttpError((Activity) baseActivity, throwable.getMessage());
            }
        });
        //语音
        btn_speach.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startSpeechRecognition(); //开始语音识别
            }
        });
        //取消
        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setClickableWithDelay(btn_cancel, 1000);//按钮禁止连点
                dialog2.dismiss();
            }
        });

        //确认
        btn_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setClickableWithDelay(btn_ok, 1000);//按钮禁止连点
                String userName = edit_name.getText().toString();
                String phoneNo = userPhone;
                if (Data.isNull(userName)) {
                    DialogUtils.show(baseActivity, "请输入姓名");
                    return;
                }
                Integer orderNum = edit_order.getText().toString().isEmpty() ? null : Integer.parseInt(edit_order.getText().toString());

                myService.updateName(phoneNo,userName,orderNum).enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        try {
                            if (response.isSuccessful()) {
                                JSONObject data = RetrofitUtil.getDataFromResponse(response);
                                if (200 == data.getInteger("code")) {
                                    DialogUtils.show(baseActivity, "修改成功");
                                    if (eventListener != null){
                                        eventListener.updateSuccess();
                                    }
                                }
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable throwable) {
                        SystemUtils.invokeHttpError((Activity) baseActivity, throwable.getMessage());
                    }
                });
                dialog2.dismiss();

            }
        });

    }

    private Handler mHandler = new Handler();
    //按钮禁止连点
    public void setClickableWithDelay(final View button, long delay) {
        button.setClickable(false);
        //button.setBackground(baseActivity.getDrawable(R.drawable.background_gradient_blue_btn2));
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                try {
                    button.setClickable(true);
                    //button.setBackground(baseActivity.getDrawable(R.drawable.background_gradient_blue_btn1));
                } catch (Resources.NotFoundException e) {
                    e.printStackTrace();
                }
            }
        }, delay);
    }

    /**
     * 语音识别
     */
    private void startSpeechRecognition() {
        try {
            if (speechRecognizer == null) {
                Toast.makeText(baseActivity, "无法创建 SpeechRecognizer 实例", Toast.LENGTH_SHORT).show();
                return;
            }
            Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
            intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
            intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "zh-CN"); // 设置为中文
            speechRecognizer.startListening(intent); // 开始监听
        } catch (Exception e) {
            DialogUtils.show(baseActivity,"暂无支持");
        }
    }

    /**
     * 权限列表
     */
    public static final String[] PERMISSIONS = new String[]{
            Manifest.permission.READ_PHONE_STATE,       // ***获取设备状态的权限，重要
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.INTERNET,
            "android.permission.BLUETOOTH_SCAN",
            "android.permission.BLUETOOTH_CONNECT",
            "android.permission.ACCESS_FINE_LOCATION",
            "android.permission.READ_PHONE_STATE",
            "android.permission.USB_PERMISSION"
    };

    private SpeechRecognizer speechRecognizer;//语音识别
    /**
     * 初始化语音权限
     */
    private void initVice() {
        // 检查并请求录音权限,申请权限
        PermissionChecker mPermissionChecker = new PermissionChecker(baseActivity);
        if (mPermissionChecker.judgePermissions(PERMISSIONS)) {
            ActivityCompat.requestPermissions((Activity) baseActivity, PERMISSIONS, 0);
        } else {

        }

        SpeechRecognizer.isRecognitionAvailable(baseActivity);
        // 初始化 SpeechRecognizer
        speechRecognizer = SpeechRecognizer.createSpeechRecognizer(baseActivity);
        // 设置监听器
        speechRecognizer.setRecognitionListener(new RecognitionListener() {
            @Override
            public void onReadyForSpeech(Bundle params) {
                Toast.makeText(baseActivity, "开始说话", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onBeginningOfSpeech() {
                // 开始说话
            }

            @Override
            public void onRmsChanged(float rmsdB) {
                // 音量变化
            }

            @Override
            public void onBufferReceived(byte[] buffer) {
                // 接收语音数据
            }

            @Override
            public void onEndOfSpeech() {
                Toast.makeText(baseActivity, "结束说话", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(int error) {
                String message;
                switch (error) {
                    case SpeechRecognizer.ERROR_AUDIO:
                        message = "音频错误";
                        break;
                    case SpeechRecognizer.ERROR_CLIENT:
                        message = "客户端错误";
                        break;
                    case SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS:
                        message = "权限不足";
                        break;
                    case SpeechRecognizer.ERROR_NETWORK:
                        message = "网络错误";
                        break;
                    case SpeechRecognizer.ERROR_NETWORK_TIMEOUT:
                        message = "网络超时";
                        break;
                    case SpeechRecognizer.ERROR_NO_MATCH:
                        message = "没有匹配的识别结果";
                        break;
                    case SpeechRecognizer.ERROR_RECOGNIZER_BUSY:
                        message = "识别服务繁忙";
                        break;
                    case SpeechRecognizer.ERROR_SERVER:
                        message = "服务器错误";
                        break;
                    case SpeechRecognizer.ERROR_SPEECH_TIMEOUT:
                        message = "未检测到语音输入";
                        break;
                    default:
                        message = "未知错误";
                        break;
                }
                Toast.makeText(baseActivity, "识别错误：" + message, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResults(Bundle results) {
                // 获取最终识别结果
                ArrayList<String> matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
                if (matches != null && !matches.isEmpty()) {
                    if (edit_name != null && edit_name.hasFocus()) {
                        edit_name.append(matches.get(0)); // 显示识别结果
                        edit_name.setSelection(edit_name.getText().length()); // 光标移动到最后
                    }

                }
            }

            @Override
            public void onPartialResults(Bundle partialResults) {
                // 获取部分识别结果
                ArrayList<String> partialMatches = partialResults.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
                if (partialMatches != null && !partialMatches.isEmpty()) {
                    if (edit_name != null && edit_name.hasFocus()) {
                        edit_name.append(partialMatches.get(0)); // 显示识别结果
                        edit_name.setSelection(edit_name.getText().length()); // 光标移动到最后
                    }
                }
            }

            @Override
            public void onEvent(int eventType, Bundle params) {
                // 其他事件
            }
        });
    }
    public final class ViewHolder extends RecyclerView.ViewHolder {
        TextView userPhone;
        TextView info;
        TextView freshTime;
        TextView signInfo;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            userPhone = itemView.findViewById(R.id.userPhone);
            info = itemView.findViewById(R.id.info);
            freshTime = itemView.findViewById(R.id.freshTime);
            signInfo = itemView.findViewById(R.id.signInfo);

        }
    }

    @Override
    public long getItemId(int index) {
        return index;
    }

    @Override
    public int getItemCount() {
        return list == null ? 0 : list.size();
    }

    public void toSign(String phoneNo){
        myService = RetrofitUtil.build(MyService.class);//初始化网络请求9
        myService.sign(phoneNo).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    if (response.isSuccessful()) {
                        JSONObject data = RetrofitUtil.getDataFromResponse(response);
                        if (200 == data.getInteger("code")) {
                            DialogUtils.show(baseActivity, "签到成功");
                            if (eventListener != null){
                                //eventListener.updateSuccess();
                            }
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable throwable) {
                SystemUtils.invokeHttpError((Activity) baseActivity, throwable.getMessage());
            }
        });
    }


}
